package com.ppt.convert;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Stack;

/**
 * @author zcx
 * @Title q
 * @date 2020年06月23日 9:19
 **/
public class Pdf2Jpg2 {
    /**
     *
     * @param filepath
     *            pdf路径
     * @param savePath
     *            img保存路径
     * @param times
     *            缩放比例 如：1f为原图比例
     * @throws IOException
     */
    public static void savaPageAsJpgByAcrobat(String filepath, String savePath,
                                              float times) throws IOException {
        ComThread.InitSTA();//初始化com的线程
        // 输出
        FileOutputStream out = null;
        // PDF页数
        int pageNum = 0;
        // PDF宽、高
        int x, y = 0;
        // PDF控制对象
        Dispatch pdfObject = null;
        // PDF坐标对象
        Dispatch pointxy = null;
        // pdfActiveX PDDoc对象 主要建立PDF对象
        ActiveXComponent app = new ActiveXComponent("AcroExch.PDDoc");
        // pdfActiveX PDF的坐标对象
        ActiveXComponent point = new ActiveXComponent("AcroExch.Point");
        try {
            // 得到控制对象
            pdfObject = app.getObject();
            // 得到坐标对象
            pointxy = point.getObject();
            // 打开PDF文件，建立PDF操作的开始
            Dispatch.call(pdfObject, "Open", new Variant(filepath));
            // 得到当前打开PDF文件的页数
            pageNum = Dispatch.call(pdfObject, "GetNumPages").toInt();

            for (int i = 0; i < pageNum; i++) {
                // 根据页码得到单页PDF
                Dispatch page = Dispatch.call(pdfObject, "AcquirePage",
                        new Variant(i)).toDispatch();
                // 得到PDF单页大小的Point对象
                Dispatch pagePoint = Dispatch.call(page, "GetSize")
                        .toDispatch();
                // 创建PDF位置对象，为拷贝图片到剪贴板做准备
                ActiveXComponent pdfRect = new ActiveXComponent("AcroExch.Rect");
                // 得到单页PDF的宽
                int imgWidth = (int) (Dispatch.get(pagePoint, "x").toInt() * 2 * times);
                // 得到单页PDF的高
                int imgHeight = (int) (Dispatch.get(pagePoint, "y").toInt() * 2 * times);
                // 控制PDF位置对象
                Dispatch pdfRectDoc = pdfRect.getObject();
                // 设置PDF位置对象的值
                Dispatch.put(pdfRectDoc, "Left", new Integer(0));
                Dispatch.put(pdfRectDoc, "Right", new Integer(imgWidth));
                Dispatch.put(pdfRectDoc, "Top", new Integer(0));
                Dispatch.put(pdfRectDoc, "Bottom", new Integer(imgHeight));
                // 将设置好位置的PDF拷贝到Windows剪切板，参数：位置对象,宽起点，高起点，分辨率
                Dispatch.call(page, "CopyToClipboard", new Object[] {
                        pdfRectDoc, 0, 0, 200 * times });
                Image image = getImageFromClipboard();
                BufferedImage tag = new BufferedImage(imgWidth, imgHeight, 8);
                Graphics graphics = tag.getGraphics();
                graphics.drawImage(image, 0, 0, null);
                graphics.dispose();
                // 输出图片
                ImageIO.write(tag, "JPEG", new File(savePath + (i+1) + ".jpg"));
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭PDF
            app.invoke("Close", new Variant[] {});
            ComThread.Release();//关闭com的线程   真正kill进程
        }

    }

    public static Image getImageFromClipboard() throws Exception {
        Clipboard sysc = Toolkit.getDefaultToolkit().getSystemClipboard();
        Transferable cc = sysc.getContents(null);
        if (cc == null)
            return null;
        else if (cc.isDataFlavorSupported(DataFlavor.imageFlavor))
            return (Image) cc.getTransferData(DataFlavor.imageFlavor);
        return null;
    }

    public static void main(String[] args) throws IOException {
        savaPageAsJpgByAcrobat("D:\\download_cqt\\9fc254ada14e4e398d72b342921df39a\\【36Kr】2020年中国企业直播研究报告.pdf",
                "D:\\zcx\\zcx", 1f);
    }
}
